<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/13
 * Time: 14:59
 */

namespace app\im\model;

/**
 * @method static Locate($user_id)
 * @method static lists($parmas)
 */
class ChatService extends ImBase
{

    // 格式化内容
    public function scopeContent($query)
    {
        // withAttr 不能再使用模型的查询方法，必须使用Db类的查询方法。
        // 不用 getContentAttr 因为避免全局应用
        $query->withAttr('content', function ($value, $data) {
            $value = str_replace('|||', ' ', $value);
            $value = subtext($value, 12);

            $array = [" ", $value, "[图片]", "[音频]"];
            return $array[$data["type"]];
        });
    }

    // 查询范围 - 常用用 where
    public static function scopeLocate($query, $user_id)
    {

        $query->where([
            'user_id' => $user_id,
            'is_del' => 0,
            'status' => 1
        ]);

    }

    // 获取最新一条消息
    public static function getTheLatest($user_id)
    {
        // 消息
        $chat = self::Locate($user_id)
            ->scope("content")
            ->order("id desc")
            ->find() ?: [];
        // 客服账号
        $user = User::get(1);
        // 未读数
        $unread_count = self::Locate($user_id)
            ->where("is_read", 0)
            ->count();

        return compact("chat", "unread_count", "user");
    }


    // 通知列表
    public static function getLists($parmas)
    {
        $user_id = $parmas["user_id"];
        $page = $parmas["page"] ?? 1;
        $limit = $parmas["limit"] ?? 10;

        // 获取记录
        $history = self::lists($parmas)->Locate($user_id)->all();
        // 是否还有更多
        $have_more = self::Locate($user_id)
                ->count() <=> $page * $limit;
        // 客服账号
        $obj_user = User::get(1);

        return compact('history', 'have_more', "obj_user");
    }

    // 设置通知已读
    public static function setReaded($user_id)
    {

        return self::where(compact("user_id"))
            ->setField("is_read", 1);

    }

}